import React, { Component } from 'react'
import './index.scss'
import View from './../view/view.js'
import Popper from './popper.js'
import ReactDOM from 'react-dom'

class Tooltip extends Component {
  constructor (props) {
    super(props)
    this.state = {
      show: false,
      children: React.cloneElement(props.children, {
        id: 'ref',
        onMouseEnter: this.onMouseEnterFn.bind(this),
        onMouseLeave: this.onMouseLeaveFn.bind(this)
      })
    }
    this.createPopper = this.createPopper.bind(this)
  }
  beforeEnterFn () {
    this.popper ? this.popper.update() : this.createPopper()
  }
  createPopper () {
    this.popper = new Popper(ReactDOM.findDOMNode(this).querySelector('#ref'), this.refs.popper, {
      placement: 'top',
      offsetFn (ref, ctn) {
        const moveLeft = (ctn.offsetWidth - ref.offsetWidth) / 2
        ctn.style.left = ctn.offsetLeft - moveLeft + 'px'
        ctn.style.top = ctn.offsetTop - 5 + 'px'
      }
    })
  }
  onMouseEnterFn () {
    this.setState({
      show: true
    })
  }
  onMouseLeaveFn () {
    this.setState({
      show: false
    })
  }
  render () {
    return(
      <div>
        { this.state.children }
        <div ref="popper">
        <View
        show={this.state.show}
        beforeEnter={this.beforeEnterFn.bind(this)}>
          { this.props.render() }
        </View>
        </div>
      </div>
    )
  }
}

export default class Demo2 extends Component {
  constructor (props) {
    super(props)
  }
  render () {
    return (
      <div className="Demo2Ctn">
        <div className="Card">
        <Tooltip render={() => {
          return(
          <div
          className="tooltip">删除dsdsdsd</div>
          )
        }}>
          <div className="icon">
            图标
          </div>
          </Tooltip>
        </div>

        <div className="Card">
        <Tooltip render={() => {
          return(
          <div
          className="tooltip">删除</div>
          )
        }}>
          <div className="icon">
            图标
          </div>
          </Tooltip>
        </div>

      </div> 
    )
  }
}